package com.ruoyi.business.controller;

import com.ruoyi.business.domain.EquipmentVariablesHistory;
import com.ruoyi.business.service.IEquipmentVariablesHistoryService;
import com.ruoyi.business.vo.EquipmentVariablesHistoryVO;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 设备变量历史数据Controller
 * 
 * @author ldkj
 * @date 2025-02-27
 */
@RestController
@RequestMapping("/business/history")
public class EquipmentVariablesHistoryController extends BaseController
{
    @Autowired
    private IEquipmentVariablesHistoryService equipmentVariablesHistoryService;

    /**
     * 查询设备变量历史数据列表
     */
    @PreAuthorize("@ss.hasPermi('business:history:list')")
    @GetMapping("/list")
    public TableDataInfo list(EquipmentVariablesHistory equipmentVariablesHistory)
    {
        startPage();
        List<EquipmentVariablesHistory> list = equipmentVariablesHistoryService.selectEquipmentVariablesHistoryList(equipmentVariablesHistory);
        return getDataTable(list);
    }

    /**
     * 根据变量ID查询历史数据列表
     */
    @PreAuthorize("@ss.hasPermi('business:history:list')")
    @GetMapping("/listByVariableId/{variableId}")
    public TableDataInfo listByVariableId(@PathVariable("variableId") Long variableId)
    {
        startPage();
        List<EquipmentVariablesHistory> list = equipmentVariablesHistoryService.selectEquipmentVariablesHistoryByVariableId(variableId);
        return getDataTable(list);
    }

    /**
     * 根据变量名称查询历史数据列表
     */
    @PreAuthorize("@ss.hasPermi('business:history:list')")
    @GetMapping("/listByVariableName/{variableName}")
    public TableDataInfo listByVariableName(@PathVariable("variableName") String variableName)
    {
        startPage();
        List<EquipmentVariablesHistory> list = equipmentVariablesHistoryService.selectEquipmentVariablesHistoryByVariableName(variableName);
        return getDataTable(list);
    }



    /**
     * 根据操作类型查询历史数据列表
     */
    @PreAuthorize("@ss.hasPermi('business:history:list')")
    @GetMapping("/listByOperationType/{operationType}")
    public TableDataInfo listByOperationType(@PathVariable("operationType") String operationType)
    {
        startPage();
        List<EquipmentVariablesHistory> list = equipmentVariablesHistoryService.selectEquipmentVariablesHistoryByOperationType(operationType);
        return getDataTable(list);
    }

    /**
     * 导出设备变量历史数据列表
     */
    @PreAuthorize("@ss.hasPermi('business:history:export')")
    @Log(title = "设备变量历史数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EquipmentVariablesHistory equipmentVariablesHistory)
    {
        List<EquipmentVariablesHistory> list = equipmentVariablesHistoryService.selectEquipmentVariablesHistoryList(equipmentVariablesHistory);
        ExcelUtil<EquipmentVariablesHistory> util = new ExcelUtil<EquipmentVariablesHistory>(EquipmentVariablesHistory.class);
        util.exportExcel(response, list, "设备变量历史数据");
    }

    /**
     * 获取设备变量历史数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:history:query')")
    @GetMapping(value = "/{historyId}")
    public AjaxResult getInfo(@PathVariable("historyId") Long historyId)
    {
        return success(equipmentVariablesHistoryService.selectEquipmentVariablesHistoryByHistoryId(historyId));
    }

    /**
     * 新增设备变量历史数据
     */
    @PreAuthorize("@ss.hasPermi('business:history:add')")
    @Log(title = "设备变量历史数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EquipmentVariablesHistory equipmentVariablesHistory)
    {
        return toAjax(equipmentVariablesHistoryService.insertEquipmentVariablesHistory(equipmentVariablesHistory));
    }

    /**
     * 修改设备变量历史数据
     */
    @PreAuthorize("@ss.hasPermi('business:history:edit')")
    @Log(title = "设备变量历史数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EquipmentVariablesHistory equipmentVariablesHistory)
    {
        return toAjax(equipmentVariablesHistoryService.updateEquipmentVariablesHistory(equipmentVariablesHistory));
    }

    /**
     * 删除设备变量历史数据
     */
    @PreAuthorize("@ss.hasPermi('business:history:remove')")
    @Log(title = "设备变量历史数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/{historyIds}")
    public AjaxResult remove(@PathVariable Long[] historyIds)
    {
        return toAjax(equipmentVariablesHistoryService.deleteEquipmentVariablesHistoryByHistoryIds(historyIds));
    }

    /**
     * 根据变量ID删除历史数据
     */
    @PreAuthorize("@ss.hasPermi('business:history:remove')")
    @Log(title = "设备变量历史数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/byVariableId/{variableId}")
    public AjaxResult removeByVariableId(@PathVariable Long variableId)
    {
        return toAjax(equipmentVariablesHistoryService.deleteEquipmentVariablesHistoryByVariableId(variableId));
    }

    /**
     * 清理指定天数之前的历史数据
     */
    @PreAuthorize("@ss.hasPermi('business:history:clean')")
    @Log(title = "清理历史数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/clean/{days}")
    public AjaxResult cleanHistoryData(@PathVariable int days)
    {
        if (days <= 0) {
            return error("保留天数必须大于0");
        }
        int result = equipmentVariablesHistoryService.cleanHistoryDataBeforeDays(days);
        return success("成功清理 " + result + " 条历史数据");
    }

    /**
     * 手动记录设备变量历史数据
     */
    @PreAuthorize("@ss.hasPermi('business:history:record')")
    @Log(title = "记录历史数据", businessType = BusinessType.INSERT)
    @PostMapping("/record")
    public AjaxResult recordHistory(@RequestBody EquipmentVariablesHistory historyRequest)
    {
        return toAjax(equipmentVariablesHistoryService.recordVariableHistory(
            historyRequest.getVariableId(),
            historyRequest.getOperationType(),
            historyRequest.getOldValue(),
            historyRequest.getNewValue()
        ));
    }

    /**
     * 查询指定6个变量在时间范围内的历史记录（返回对象列表）
     */
    @Anonymous
    @GetMapping("/sixVariablesByTimeRange")
    public AjaxResult getSixVariablesByTimeRange(@RequestParam("experimentDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date experimentDate,
                                                 @RequestParam("startTime") String startTimeStr,
                                                 @RequestParam("endTime") String endTimeStr) throws ParseException {
        // 将日期 + 时分拼成完整 Date
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date startDate = sdf.parse(new SimpleDateFormat("yyyy-MM-dd").format(experimentDate) + " " + startTimeStr);
        Date endDate = sdf.parse(new SimpleDateFormat("yyyy-MM-dd").format(experimentDate) + " " + endTimeStr);

        List<String> variableEnNames = Arrays.asList(
                "waterCoolActualtempu",
                "waterCoolActualfloww",
                "waterCoolActualflows",
                "waterCoolActualpreso",
                "waterCoolAiractflow",
                "waterCoolActualpresc"
        );

        List<EquipmentVariablesHistoryVO> list = equipmentVariablesHistoryService.
                getVariablesHistoryByTimeRange(startDate, endDate, variableEnNames);
        return AjaxResult.success(list);
    }


    /**
     * 实验平台管理->>富氧四级页面->>历史数据
     * @param experimentDate
     * @param startTimeStr
     * @param endTimeStr
     * @return
     * @throws ParseException
     */
    @Anonymous
    @GetMapping("/getOxygenRichHistory")
    public AjaxResult getOxygenRichHistory(@RequestParam("experimentDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date experimentDate,
                                                 @RequestParam("startTime") String startTimeStr,
                                                 @RequestParam("endTime") String endTimeStr) throws ParseException {
        // 将日期 + 时分拼成完整 Date
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date startDate = sdf.parse(new SimpleDateFormat("yyyy-MM-dd").format(experimentDate) + " " + startTimeStr);
        Date endDate = sdf.parse(new SimpleDateFormat("yyyy-MM-dd").format(experimentDate) + " " + endTimeStr);

        List<String> variableEnNames = Arrays.asList(
                "mildMildfurntemp",
                "mildMildfurntemp1",
                "mildMildfurntemp2",
                "mildMildfurntemp3",
                "mildMildfurnperf1",
                "mildMildfurnactu2",
                "mildMildfurnactu6",
                "mildMildfurnactu4",
                "mildMildfurnactu8",
                "mildMildfurnperf",
                "mildMildfurnactu",
                "mildMildfurnactu1"
        );

        List<EquipmentVariablesHistoryVO> list = equipmentVariablesHistoryService.
                getVariablesHistoryByTimeRange(startDate, endDate, variableEnNames);
        return AjaxResult.success(list);
    }

    /**
     * 实验平台管理->>立式四级页面->>历史数据
     * @param experimentDate
     * @param startTimeStr
     * @param endTimeStr
     * @return
     * @throws ParseException
     */
    @Anonymous
    @GetMapping("/getVertFourthHistory")
    public AjaxResult getVertFourthHistory(@RequestParam("experimentDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date experimentDate,
                                           @RequestParam("startTime") String startTimeStr,
                                           @RequestParam("endTime") String endTimeStr) throws ParseException {
        // 将日期 + 时分拼成完整 Date
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date startDate = sdf.parse(new SimpleDateFormat("yyyy-MM-dd").format(experimentDate) + " " + startTimeStr);
        Date endDate = sdf.parse(new SimpleDateFormat("yyyy-MM-dd").format(experimentDate) + " " + endTimeStr);

        List<String> variableEnNames = Arrays.asList(
                "multiFuncRadiationtu3",
                "multiFuncRadiationtu1",
                "multiFuncRadiationtu6",
                "multiFuncRadiationtu4",
                "multiFuncRadiationtu",
                "multiFuncRadiationtu2"
        );

        List<EquipmentVariablesHistoryVO> list = equipmentVariablesHistoryService.
                getVariablesHistoryByTimeRange(startDate, endDate, variableEnNames);
        return AjaxResult.success(list);
    }

}